export const KEY = 'goodsinfo';
//localStorage.setItem(key,value)
export function setitem(value){
    var str = getitem(KEY);
    str.push(value);
    str = JSON.stringify(str);  
    localStorage.setItem(KEY,str);
};
//localStorage.getItem(key)
export function getitem(){
    var arr = localStorage.getItem(KEY);
    arr = arr || '[]';
    return  JSON.parse(arr);
}
//localStorage.renoveItem(key)
export function remove(){

}
//格式化取到的数据为{87:9}的格式
export function dataobj(){
    var data = getitem();        //data是对象组成的数组
          var dataobj = {};
    for(var i = 0; i < data.length; i++){
        var temp = data[i];
         if(!dataobj[temp.goodsid]){
            dataobj[temp.goodsid] = temp.counts;
        }else{
            dataobj[temp.goodsid] += temp.counts;
        } 
        //console.log(123,temp)
    }
   return dataobj; 
}
//更新localStorage中的数据
export function updateloca(obj){
    //先获取localStorage中的数据
    var arr = getitem()
    //console.log(1,arr);
    for(var i = 0; i < arr.length; i++){
        if(obj.goodsid == arr[i].goodsid){
            if(obj.type == 'jia'){
                if(arr[i].goodsid){
                    arr[i].counts++;
                }else{
                    arr.push({'goodsid':arr[i].goodsid,'counts':1})
                    break;
                }
               
            }else{
                if(arr[i].counts > 1){
                    arr[i].counts--;
                    break;  
                }else{
                    arr.splice(i,1)
                }
            }
        }
    }
    localStorage.setItem('goodsinfo',JSON.stringify(arr))
}